package com.bejoy.config.handler;


import cn.hutool.json.JSONUtil;
import com.bejoy.common.AjaxResult;
import com.bejoy.common.Constants;
import com.bejoy.domain.model.TUser;
import com.bejoy.service.RedisService;
import com.bejoy.util.JWTUtils;
import com.bejoy.util.ResponseUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {

    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        TUser tUser = (TUser) authentication.getPrincipal();

        // 生成jwt保存到redis中
        String userString = JSONUtil.toJsonStr(tUser);
        String jwt = JWTUtils.createJWT(userString);
        redisService.setValue(Constants.REDIS_JWT_KEY + tUser.getId(),jwt);

        // 设置过期时间
        redisService.expire(Constants.REDIS_JWT_KEY + tUser.getId(),Constants.DEFAULT_EXPIRE_TIME, TimeUnit.SECONDS);

        // 登录结果返回给前端
        AjaxResult result = AjaxResult.success(jwt);

        String jsonStr = JSONUtil.toJsonStr(result);

        ResponseUtils.write(response,jsonStr);
    }
}
